package cn.ivicar.guice;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;

public class GuiceConfig extends GuiceServletContextListener {
    private static GuiceConfig staticInstance = null;

    protected GuiceLifecycleListener guiceLifecycleListener;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        super.contextInitialized(servletContextEvent);
        setStaticInstance(this);

        this.guiceLifecycleListener = new GuiceLifecycleListener();
        this.guiceLifecycleListener.contextInitialized(servletContextEvent);
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        super.contextDestroyed(servletContextEvent);
        if (this.guiceLifecycleListener != null) {
            this.guiceLifecycleListener.contextDestroyed(servletContextEvent);
        }
    }

    public static GuiceConfig getStaticInstance() {
        return staticInstance;
    }

    public static void setStaticInstance(GuiceConfig guiceConfig) {
        staticInstance = guiceConfig;
    }

    public static Injector getStaticInjector() {
        Injector injector = null;

        if (getStaticInstance() != null) {
            injector = getStaticInstance().getInjector();
        }

        return injector;
    }

    @Override
    public Injector getInjector() {
        Map<String, String> resourceBindings = new HashMap<String, String>();
        return Guice.createInjector(
            new GuiceServletModule("cn.ivicar.cloud",
                "cn.ivicar.cloud", resourceBindings, true));
    }
}
